// 引入mongoose
const mongoose = require('mongoose')
const md5 = require('md5')
const userModel = require('./models/UserModel')

// 暴露
module.exports = () => {
    // 开启服务
    const promise = mongoose['connect']('mongodb://localhost:27017/user_manage')

    // 绑定监听
    mongoose['connection'].on('open', async () => {
        console.log('链接数据库成功')
        // 查找数据库中有没有admin用户，没有就创建一个
        const user = await userModel.findOne({ username: 'admin' })
        // console.log(users)
        if (!user) {
            await userModel.create({
                username: 'admin',
                pwd: md5('111111'),
                profile: '/upload/admin.png'
            })
        }
    })
    mongoose['connection'].on('error', () => {
        console.log('链接数据库失败')
    })
    // 返回promise
    return promise
}
